package com.taobao.machinesystem.controller;

import com.taobao.machinesystem.anno.MachineLog;
import com.taobao.machinesystem.common.Result;
import com.taobao.machinesystem.common.SystemConst;
import com.taobao.machinesystem.entity.SysUser;
import com.taobao.machinesystem.entity.vo.SysPermissionVo;
import com.taobao.machinesystem.service.SysPermissionService;
import com.taobao.machinesystem.service.SysUserService;
import com.taobao.machinesystem.utilis.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
public class IndexRestController {

    @Autowired
    private SysPermissionService sysPermissionService;


    @Autowired
    private SysUserService sysUserService;

    /**
     * 验证登录
     * @return Result
     */
    @MachineLog(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody SysUser user, HttpSession session) {
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), MD5Utils.changePasswordMD5(user.getPassword()));
        try{
            //执行登录方法,如果没有异常，说明ok
            subject.login(token);
            return Result.ok().setMessage(SystemConst.LOGIN_SUCCESS);
        }catch (UnknownAccountException e){
            //用户名不存在
            return Result.error().setMessage(SystemConst.LOGIN_FAIL);
        }catch (IncorrectCredentialsException e){
            //密码错误
            return Result.error().setMessage(SystemConst.LOGIN_FAIL);
        }
    }

    /**
     * 获取用户相对应的权限菜单
     * @return Result
     */
    @GetMapping("/menuList")
    public Result menuList() {
        List<SysPermissionVo> sysPermissionVos = sysPermissionService.findByMenuListByUserId("1");
        return Result.ok().setMapValue("items", sysPermissionVos);
    }

    /**
     * 获取用户信息接口
     * @return Result
     */
    @GetMapping("/userInfo")
    public Result getUserInfo(){
        SysUser sysUser = sysUserService.selectByIdSysUser("");
        return Result.ok().setMapValue("item",sysUser);
    }

    /**
     * 获取主页菜单
     * @return
     */
    @PostMapping("/getMenuList")
    public Result getMenuList(){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser) subject.getPrincipal();
        List<SysPermissionVo> menuList = sysPermissionService.findByMenuListByUserId(sysUser.getId());
        return Result.ok().setMapValue("items",menuList).setMapValue("sysUser",sysUser).setMessage(SystemConst.SELECT_SUCCESS);
    }
}


